package com.demo.paypalmanagement.common;

import com.demo.paypalmanagement.model.entity.Order;
import com.demo.paypalmanagement.model.entity.OrderItems;
import com.demo.paypalmanagement.model.entity.Products;
import com.demo.paypalmanagement.model.vo.OrderItemVO;
import com.demo.paypalmanagement.model.vo.OrderVO;
import com.demo.paypalmanagement.service.IOrderItemsService;
import com.demo.paypalmanagement.service.IOrderService;
import com.demo.paypalmanagement.service.IProductsService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {


    @Resource
    private IOrderService orderService;

    @Resource
    private IOrderItemsService orderItemsService;

    @Resource
    private IProductsService productsService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }


    @Override
    public void onMessage(Message message, byte[] pattern) {
        log.info("过期redis数据：" + message.toString());
        try {
            String key = message.toString();
            if (StringUtils.isBlank(key) || !key.contains(RedisConstants.ORDER_KEY_PREFIX)) {
                return;
            }
            key = key.replace(RedisConstants.ORDER_KEY_PREFIX, "");
            OrderVO vo = new OrderVO();
            vo.setToken(key);
            Order one = orderService.getOne(BuildQuery.buildOrderQuery(vo));
            if (ObjectUtils.isEmpty(one)) {
                log.error("【修改支付订单" +one.getPayOrderNo() + "过期状态异常】：" + "未查询到订单数据");
                return;
            }
            one.setStatus(3);
            orderService.updateById(one);
            OrderItemVO itemVO = new OrderItemVO();
            itemVO.setOrderId(one.getOrderId());
            List<OrderItems> list = orderItemsService.list(BuildQuery.buildOrderItemQuery(itemVO));

            if (CollectionUtils.isEmpty(list)){
                log.error("订单" + one.getPayOrderNo() + "：订单项为空");
                return;
            }
            Map<Long, Integer> qtyMap = list.stream().collect(Collectors.toMap(OrderItems::getProductId, OrderItems::getQuantity, Integer::sum));

            List<Products> productsList = productsService.listByIds(qtyMap.keySet());
            if (CollectionUtils.isEmpty(productsList)) {
                log.error("订单" + one.getPayOrderNo() + "：产品为空");
                return;
            }
            for (Products products : productsList) {
                Integer num = qtyMap.get(products.getId());
                products.setStockQuantity(ObjectUtils.isEmpty(num)? 0 : num + products.getStockQuantity());
            }
            productsService.updateBatchById(productsList);

            log.info("订单号为【" + one.getPayOrderNo() + "】超时未支付-*****");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【修改支付订单过期状态异常】：" + e.getMessage());
        }
    }
}